const { userInfo } = require('os');
const request = require('request')
const AK = "Bxo0zqyiM9FAvWlQX8teceMx"
const SK = "aKZgu11X2r6ExaaexWASAkLIc3SxrYbm"

async function main() {
    console.log("开始执行。。。")
    var options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=' + await getAccessToken(),
        'headers': {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json'
        },
        form: {
            'messages':[{'role':'user','content':'中国有多大'}],
            'stream':true
        }
    };

    request(options, function (error, response) {
        if (error) throw new Error(error);
        console.log(response.body);
    });
}

/**
 * 使用 AK，SK 生成鉴权签名（Access Token）
 * @return string 鉴权签名信息（Access Token）
 */
function getAccessToken() {

    let options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
    }
    return new Promise((resolve, reject) => {
        request(options, (error, response) => {
            if (error) { reject(error) }
            else {
                console.log(JSON.parse(response.body))
                 resolve(JSON.parse(response.body).access_token) }
        })
    })
}
main();
